import axios, { AxiosInstance } from 'axios'
import router from '@/router/index'
import { ElMessage } from 'element-plus'

const http: AxiosInstance = axios.create({
    baseURL: '/',
    // baseURL: 'http://192.168.0.90:9600/',
    timeout: 30 * 1000,
    headers: {
        'Content-Type': 'application/json'
    }
})
http.interceptors.request.use((config) => {
    let token = localStorage.getItem('token')
    if (config.headers && token) {
        // 获取当前时间戳
        const timestamp = new Date().getTime().toString()
        config.headers['CY-TOKEN'] = btoa(timestamp + token)
        // config.headers['CY-TOKEN'] = token
    }
    if (config.method == 'post') {
        config.data = JSON.stringify(config.data)
    } else if (config.method == 'file') {
        //文件上传
        if (config.headers) {
            config.headers['content-type'] = 'multipart/form-data'
        }
        var formData = new FormData()
        for (var i in config.data) {
            if (config.data[i] instanceof Array) {
                config.data[i].forEach((item: any, index: Number) => {
                    for (var j in item) {
                        formData.append(i + '[' + index + '][' + j + ']', item[j])
                    }
                })
            } else {
                formData.append(i, config.data[i])
            }
        }
        config.method = 'post'
        config.data = formData
    } else if (config.method == 'get') {
        // config.query = {}
        // config.params = config.query
    } else if (config.method == 'delete') {
        // config.params = config.query
    }
    return config
})

http.interceptors.response.use(
    ({ data }) => {
        if (window.location.hash == '#/hello') {
            // console.log(document.referrer)
            if (window.location.hash == '#/hello') {
                if (data.code == 0) {
                    ElMessage.error(data.msg)
                }
                return data
            } else {
                router.push('/hello')
            }
        } else {
            // const data = response.data;
            if (data.code == 1001) {
                //未登录
                router.push('/login')
            } else {
                if (data.code == 0) {
                    ElMessage.error(data.msg)
                }
                return data
            }
        }

    },
    error => {
        ElMessage.error("服务错误")
        return error
    }
)
export default http